<?php

namespace App\Http\Services;

use App\Http\Model\FinanceDiamond;
use App\Http\Model\Hint;
use App\Http\Model\Mall;
use App\Http\Model\MallSku;
use App\Http\Model\User;
use App\Http\Model\FinanceUserWallet;
use App\Http\Model\FinanceWealth;
use Exception;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Laravel\Lumen\Http\Request;
use App\Http\Services\UserCoolvalServices;

/*商城service层*/

class MallServices extends CommonServices
{
    protected $user;
    protected $mallGoods;
    protected $mallGoodsSku;
    protected $userWallet;
    protected $diamond;
    protected $wealth;

    public function __construct()
    {
        parent::__construct();

        $this->user = new User;
        $this->mallGoods = new Mall;
        $this->mallGoodsSku = new MallSku;
        $this->userWallet = new FinanceUserWallet;
        $this->diamond = new FinanceDiamond;
        $this->wealth = new FinanceWealth;
    }

    public function getMallNav($mall_goods_class=0)
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [
            ['mall_goods_class' => 1, 'class_title'=>'钻石购买'],
            ['mall_goods_class' => 2, 'class_title'=>'活动限定'],
            ['mall_goods_class' => 3, 'class_title'=>'特权专属'],
        ];
        if ($mall_goods_class){
            $column = array_column($data, NULL, 'mall_goods_class');
            $data = $column[$mall_goods_class] ?? [];
        }

        return compact('code', 'msg', 'data');
    }

    //商品列表
    public function getGoodsList($goods_type, $page, $page_size, $is_cp = 0, $mall_goods_class=0)
    {
        $goodsList = $this->mallGoods->getGoodsListData($goods_type, $page, $page_size ,$is_cp, $mall_goods_class);
        if ($is_cp) {
            $result = [];
            foreach ($goodsList as $key => $value) {
                $findGoodId = $value['goods_id'];

                //查询绑定数据
                $goodInfo = array_filter($goodsList, function ($param) use ($findGoodId) {
                    return $param['give_data_id'] == $findGoodId;
                });

                if ($goodInfo) {
                    $keys = array_keys($goodInfo);
                    unset($goodsList[$key]);
                    $goodInfo = array_values($goodInfo);

                    $goodData[0] = $value;
                    $goodData[1] = $goodInfo[0];

                    $result[] = $goodData;
                }

            }

            $goodsList = $result;
        }
        return ['list'=>$goodsList,'page_index'=>$page,'page_count'=>count($goodsList),'page_size'=>$page_size];
    }

    /**
     *
     * 商品列表 普通+CP商品 2.5.0
     * @param $goods_type
     * @param $page
     * @param $page_size
     * @param int $mall_goods_class
     * @return array
     *
     */
    public function getGoodsListV1($goods_type, $page, $page_size, $mall_goods_class=0)
    {
        $goodsList = $this->mallGoods->getGoodsList($goods_type, $page, $page_size , $mall_goods_class);
            $result = [];
            if ($goodsList){

                $userId = $this->currentUserId;

                # 用户炫酷值等级
                /*$UserCoolvalServices  = new UserCoolvalServices();
                $resUserCoolInfo = $UserCoolvalServices -> getUserCoolInfo($userId);
                $UserCoolInfo = [];
                if ($resUserCoolInfo && $resUserCoolInfo['data']){
                    $UserCoolInfo['cool_val'] = $resUserCoolInfo['data']['cool_val'] ?? 0;
                    $UserCoolInfo['level_info'] = $resUserCoolInfo['data']['level_info'] ?? 0;
                }*/

                $levelResule = (new GoodsLevelServices())->getGoosLevelList([]);
                $levelList = [];
                if ($levelResule && $levelList =$levelResule['data']){
                    $levelList = array_column($levelList, NULL, 'level');
                }

                foreach ((array)$goodsList as $key => $value) {
                    $goodsList[$key]['level_info'] = (object) $value['level_info'];
                    //查询绑定数据 - 情侣商品
                    $give_goods_info = [];
                    $give_data_id = $value['give_data_id'] ?? 0;
                    if ($give_data_id){
                        $give_good = $this->mallGoods->get_goods($give_data_id ,0);
                        if ($give_good && $give_good['give_data_id'] == $value['goods_id'] ){
                            $give_level_info = $levelList[$give_good['level']] ?? [];
                            $give_good['level_info'] = (object) $give_level_info;
                            // 情侣商品相互绑定 有效，否则视为普通商品
                            $give_goods_info = $give_good;
                        }
                    }
                    $goodsList[$key]['give_goods_info'] = (object) $give_goods_info;
                    //$goodsList[$key]['user_cool_info'] = (object) $UserCoolInfo;
                }
            }

        return ['list'=>$goodsList,'page_index'=>$page,'page_count'=>count($goodsList),'page_size'=>$page_size];
    }

    //用户商品列表
    public function getUserGoodsList($userId, $goods_type, $page, $page_size, $goods_status='valid')
    {
        $goodsList = $this->mallGoods->getUserGoodsList($userId, $goods_type, $page, $page_size, $goods_status);
        if ($goodsList){
            $GoodsIncomeServise = new GoodsIncomeServices();
            foreach ((array)$goodsList as $key => $value) {

                if ($value['is_use']==1 && $value['end_timestamp'] < time() ){
                    $goodsList[$key]['is_use'] = 0;// 过期则佩戴状态重置
                }

                $goodsList[$key]['sku_list'] = $this->mallGoods->getSkuDataByGoods($value['goods_id']);

                $goodsList[$key]['goods_debris_num'] = $this -> get_goods_debris_num($value['debris_num'], $value['end_timestamp']);
                //$goodsList[$key]['user_cool_info'] = (object)$UserCoolInfo;
                $goodsList[$key]['level_info'] = (object)$value['level_info'];


                $userUpgradeLevelInfo = [];
                $upgradeInfo = [];
                if ($value['is_upgrade']){
                    $upgradeInfo = $GoodsIncomeServise->getUserGoodsUpgradeInfo($userId, $value['goods_id']);
                }
                if ($upgradeInfo && $upgradeInfo['code']==Hint::SUCCESS){
                    $userUpgradeLevel = $upgradeInfo['data']['upgrade_info']['level'] ?? 0;// 经验匹配等级
                    $userUpgradeIncome = $upgradeInfo['data']['income'] ?? 0;

                    $userUpgradeLevelInfo['income'] = $userUpgradeIncome;// 佩戴经验
                    $userUpgradeLevelInfo['use_upgrade_level'] = $value['use_upgrade_level'] > $userUpgradeLevel ? 0 : $value['use_upgrade_level'];// 佩戴等级
                    $userUpgradeLevelInfo['user_upgrade_level_max'] = $userUpgradeLevel;// 经验匹配等级
                }
                $goodsList[$key]['user_upgrade_level'] = (object)$userUpgradeLevelInfo;

                // 处理佩戴状态
                if ( $value['upgrade_config']){
                    foreach ($value['upgrade_config'] as $cK => $cV){
                        // 使用状态
                        $is_use = 0;
                        if ($userUpgradeLevelInfo && $cV['level'] == $userUpgradeLevelInfo['use_upgrade_level']){
                            $is_use = 1;
                            if ($cV['img']){
                                $goodsList[$key]['small_img'] = $goodsList[$key]['big_img'] = $cV['img'];
                            }
                            if ($cV['animate']){
                                $goodsList[$key]['animate_resource'] = $cV['animate'];
                            }

                        }
                        $goodsList[$key]['upgrade_config'][$cK]['is_use'] = $is_use;

                        // 解锁状态
                        $is_unlock = 0;
                        if ($userUpgradeLevelInfo && $cV['level'] <= $userUpgradeLevelInfo['user_upgrade_level_max']){
                            $is_unlock = 1;
                        }
                        $goodsList[$key]['upgrade_config'][$cK]['is_unlock'] = $is_unlock;
                    }
                }

            }
        }
        return ['list'=>$goodsList,'page_index'=>$page,'page_count'=>count($goodsList),'page_size'=>$page_size];
    }

    private function get_goods_debris_num($debris_num, $end_time)
    {
        $goods_debris_num = 0;
        // 碎片数量
        $days = caclValidDayNum($end_time);
        if ( $days > 0 ){
            $goods_debris_num = $debris_num * $days;
        }

        return $goods_debris_num;
    }

    //商品购买或赠送
    public function shoppingService(&$act_type, $goods_id, $sku_id, &$to_user_id = 0, &$cur_user_id, &$give_good_id = 0)
    {
        $user = $this->user->get_current_user();
        $cur_user_id = $user['user_id'];
        if (empty($user)) {
            return false;
        }
        if ($act_type == 2) {
            if ($user['user_id'] == $to_user_id) {//自己送自己
                return false;
            }
        }

        $goodsData = $this->mallGoods->get_goods($goods_id, 0);// 产品沟通，隐藏无需在此环节验证
        $cool_val = (int)$goodsData['cool_val'];
        $cool_val_give = 0;

        //让产品都可以购买
//        if ($goodsData['goods_type'] == 2 && $goodsData['goods_id'] <= 194){
//            return Hint::WAIT_OPEN;
//        }
        //临时解决ios传错参数（赠送 act_type传3改为2）
        if($goodsData['goods_type'] == 3 && $act_type == 3){
            $act_type = 2;
        }
        //情侣购买
        if ($act_type == 3) {
            return false;
        }

        $skuData = $this->mallGoods->getSkuData($goods_id,$sku_id);

        if(empty($skuData)){
            return false;
        }
        $wallet = $this->userWallet->get_wallet($user['user_id']);
        if(empty($wallet)){
            return false;
        }

        //钱包是否足以支付
        $price = intval($skuData['price']);
        if( $wallet['diamond_balance'] < $price ){
            return Hint::DIAMOND_NOT_ENOUGH;
        }
        DB::beginTransaction();
        if ($act_type != 3) {
            //商品
            $ret_data = $this->mallGoods->shoppingAct(
                $user['user_id'],
                $to_user_id,
                $goods_id,
                $skuData['goods_name'],
                $skuData['goods_type'],
                $skuData['sku_id'],
                $skuData['time_limit'],
                $price,
                $skuData['time_limit']*24*60*60,
                time(),
                $act_type
            );
        } else {
            $skuData = $this->mallGoods->getSkuData($goods_id,$sku_id);
            //商品
            $ret_data = $this->mallGoods->shoppingAct(
                $user['user_id'],
                0,
                $goods_id,
                $skuData['goods_name'],
                $skuData['goods_type'],
                $skuData['sku_id'],
                $skuData['time_limit'],
                $price,
                $skuData['time_limit']*24*60*60,
                time(),
                1
            );

            $giveGoodsData = $this->mallGoods->get_goods($goodsData['give_data_id'], 0);
            $skuData['goods_name'] = $giveGoodsData ? $giveGoodsData['goods_name'] : "";
            $cool_val_give = (int)$giveGoodsData['cool_val'];
            //商品
            $this->mallGoods->shoppingAct(
                $user['user_id'],
                $to_user_id,
                $goodsData['give_data_id'],
                $skuData['goods_name'],
                $skuData['goods_type'],
                $skuData['sku_id'],
                $skuData['time_limit'],
                $price,
                $skuData['time_limit']*24*60*60,
                time(),
                3
            );

            $give_good_id = $goodsData['give_data_id'];
        }

        $config = config('pay');
        $diamond_desc = $config['wallet_change_desc']['shopping_consume_diamond'];
        $ratio = $config['wallet_change_ratio']['diamond_to_wealth'];
        //钻石
        $this->diamond->inc($user['user_id'],$to_user_id,'',2,0-$price,$diamond_desc);
        //购买商品取消增加财富值
        //$this->wealth->inc($user['user_id'],$to_user_id,'',2,intval($price*$ratio));
        DB::commit();

        return $ret_data;
    }

    //商品装扮 $id 表主键id
    public function setGoodsAttireService($userId, $id, &$goodsType, $upgrade_level=0)
    {
        $upgrade_level = (int)$upgrade_level;
        //查询是否有效拥有该商品
        $checkRet = $this->mallGoods->getGoodsAttrie($userId,$id);
        if(empty($checkRet)){
            return Hint::NOW_GOODS_DISABLED;//5001
        }
        if ($upgrade_level){
            $goodsInfo = $this->mallGoods->get_goods($checkRet['goods_id'], 0);
            if(empty($goodsInfo)){
                return Hint::MALL_GOODS_LOWER;
            }
            if (!$goodsInfo['is_upgrade']){
                return Hint::MALL_GOODS_NOT_UPGRADE;
            }
            // 获取用户 该商品等级
            $GoodsIncomeServise = new GoodsIncomeServices();
            $userUpgradeLevel = 0;
            $upgradeInfo = $GoodsIncomeServise->getUserGoodsUpgradeInfo($userId, $goodsInfo['goods_id']);
            if ($upgradeInfo && $upgradeInfo['code']==Hint::SUCCESS){
                $userUpgradeLevel = $upgradeInfo['data']['upgrade_info']['level'] ?? 0;
            }
            if ($upgrade_level>$userUpgradeLevel){
                return Hint::MALL_GOODS_UPGRADE_CONFIG_ERR;
            }

        }

        $goodsType = $checkRet['goods_type'];
        $ret = $this->mallGoods->setGoodsAttrie($userId,$id,$goodsType, $upgrade_level);
        if(!$ret){
            return Hint::ERROR;
        }

        // 佩戴装扮 更新任务
        //(new GoodsIncomeServices()) -> taskUserGoodsIncomeChange($userId, $id, '佩戴装扮');

        return Hint::SUCCESS;
    }

    /**
     * 取消装扮
     * @param $goodsType
     * @return bool|int
     */
    public function cancelGoodsAttireService($goodsType, $userId){
        $ret = $this->mallGoods->cancelGoodsAttrie($userId,$goodsType);
        return $ret;
    }
    /**
     * 过期作废装扮
     * @param $userId
     * @param $goodsIds ,分割
     * @return bool|int
     */
    public function onVoidUserGoods($userId, $goodsIds){
        $userId = (int) $userId;
        if($userId<=0 ||empty($goodsIds)){
            return false;
        }
        $goodsIdArr = explode(',', $goodsIds);
        $ret = $this->mallGoods->onVoidGoodsAttrie($userId, $goodsIdArr);

        return $ret;
    }

    //当前使用的装扮
    public function getUsedAttireService($userId)
    {
        //查询已设置的商品
        $r = $this->mallGoods->getGoodsAttire($userId);
        return $r;
    }
    
    /**
     * 获取其他人装扮信息
     */
    public function getOtherUserAttire($user_id)
    {
        $userId = $user_id;

        //查询已设置的商品
        $r = $this->mallGoods->getGoodsAttire($userId);
        return $r;
    }
    /**
     * 获取预加载资源
     * @return array
     */
    public function get_animate_resources(){
        return $this->mallGoods->get_animate_resources();
    }

    /**
     * 赠送商品可以赠送多人，用逗号隔开
     * @return array
     */
    public function back_send_goods(Request $request){

        $to_user_ids = explode(',',$request->input('to_user_id'));
        $users = $this->user->get_users_by_ids($to_user_ids);
        $valid_to_user_ids = array_column($users,'user_id');
        $goods_id = $request->input('goods_id');
        $goodsInfo = $this->mallGoods->get_goods($goods_id, 0);
        $cool_val = (int) ($goodsInfo['cool_val']??0);
        $goods_name = $goodsInfo['goods_name'] ?? '';
        $goods_type = $goodsInfo['goods_type'] ?? 0;

        $serviceUcv = new UserCoolvalServices();

        foreach ($valid_to_user_ids as $to_user_id){
            try {
            DB::beginTransaction();
            $ret = $this->mallGoods->shoppingAct(
                $request->input('user_id'),
                $to_user_id,
                $request->input('goods_id'),
                $goods_name,
                $goods_type,
                $request->input('sku_id'),
                $request->input('time_limit'),
                0,
                $request->input('time_limit') * 24 * 60 * 60,
                time(),
                2
            );
            DB::commit();

            }catch (\Exception $e){
                write_log('sendGoods','sendGoods error request',json_encode($request->all()));
                write_log('sendGoods','sendGoods errorInfo',$e->getMessage());
            }

        }
        return empty($ret) ? 0 : $ret;
    }

    public function labelDel()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            try {
                $this->I('id', '标签ID', 'int', true, '标签ID不能为空');

                $variables = [];
                $checkParams = $this->check($this->requestData, $variables); //校验数据
                extract($checkParams);
                if ($code !== Hint::SUCCESS) {
                    break;
                }
                extract($variables); //数组参数化

                // 删除商品标签数据
                $this->mallGoods->table = 'mall_goods_label';
                $ret = $this->mallGoods->singleRemove($this->requestData);
                if (!$ret) {
                    $code = Hint::ERR_DATA_REMOVE_FAIL;
                    $msg = '商品标签' . Hint::getErrCodeMsg($code);
                    break;
                }

            } catch (\Exception $e) {
                $code = Hint::ERR_SYS_FAIL;
                $msg = 'message：' . $e->getMessage() . '，line：' . $e->getLine();
                break;
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 活动返现 赠送用户商品
     * */
    public function giveUserGoods($params=[]){
        $code = Hint::SUCCESS;
        $data = [
            'request_params' => $params,
        ];

        do {
            try {
                $userId = intval($params['user_id'] ?? 0);
                $goodsId = intval($params['goods_id'] ?? 0);
                $goodsType = intval($params['goods_type'] ?? 0);
                $timeLimit = intval($params['time_limit'] ?? 0);
                $sourceType = intval($params['source_type'] ?? 0);
                if (empty($userId) or empty($goodsId) or empty($goodsType) or empty($timeLimit)) {
                    $code = Hint::ERR_PARAMS_CHECK_FAIL;
                    break;
                }

                // 查询商品
                $data['goods_data'] = $this->mallGoods->get_goods($goodsId);
                if (empty($data['goods_data'])) {
                    $code = Hint::ERR_FAIL;
                    $data['error_msg'] = '查询商品失败';
                    break;
                }

                // 查询商品规格
                $data['goods_sku_data'] = $this->mallGoods->getSkuDataByGoods($goodsId);
                $goodsSku = [];
                foreach ($data['goods_sku_data'] as $value) {
                    if ($value['time_limit'] == $timeLimit) {
                        $goodsSku = $value;
                        break;
                    }
                }

                // 增加到用户商城
                DB::beginTransaction();
                $data['shopping_act'] = $this->mallGoods->shoppingAct($userId, $userId, $goodsId, $data['goods_data']['goods_name'], $data['goods_data']['goods_type'], $goodsSku['sku_id'] ?? 0, $timeLimit, 0, $timeLimit * 24 * 3600, time(), 3, $sourceType);
                DB::commit();
                if (empty($data['shopping_act']) or empty($data['shopping_act']['id'] ?? '')) {
                    $code = Hint::ERR_FAIL;
                    $data['error_msg'] = '增加到用户商城失败';
                    break;
                }

            }catch (\Exception $e){
                $code = Hint::ERR_SYS_FAIL;
                $data['error_msg'] = Hint::getErrCodeMsg($code).':'.$e->getMessage();
                break;
            }
        }while(false);

        return compact('code','data');
    }

    ################# 后台调用 ##########################################

    /**
     * 商品创建
     * */
    public function goodsCreate()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            try {
                $this->I('goods_name', '商品名称', 'string', true, '商品名称不能为空');
                $this->I('goods_type', '商品类型', 'int', false, '商品类型不能为空');// 0:其他 1:头饰 2:进场特效 3:气泡
//                $this->I('is_new', '是否新品', 'int', false, '是否新品不能为空');// 0:否 1:是
                $this->I('is_show', '是否显示商品', 'int', false);// 0:否 1:是
                $this->I('is_new_mount', '是否是新进场特效', 'int', false);// 0:否 1:是
                $this->I('text_color', '进场条字体颜色', 'string', false);
                $this->I('sort', '商品显示排序', 'int', false);// 值越大越靠前
                $this->I('big_img', '预览图片 (大图)', 'string', true,'预览图片 (大图)不能为空');
                $this->I('small_img', '展示图片（小图）', 'string', true,'展示图片（小图）不能为空');
                $this->I('animate_resource', '动画资源包链接', 'string', true,'动画资源包链接不能为空');
                $this->I('animate_resource_md5', '动画资源md5值', 'string', false);
                $this->I('animate_resource_small', '动画资源链接（默认小资源）', 'string', false);
                $this->I('animate_resource_big', '动画资源链接（新资料卡资源）', 'string', false);
                $this->I('vapc_json_url', '动画vapc资源', 'string', false);
                $this->I('give_data_id', 'give_data_id', 'int', false);
                $this->I('goods_desc', '商品描述', 'string', false);
                $this->I('is_buy', '是否需要购买', 'int', false); //1:是 0:否
                $this->I('from_url', '获取途径url', 'string', false);
                $this->I('from_desc', '获取途径描述', 'string', false);
                $this->I('label_id', '标签ID', 'string', false);
                $this->I('url_start_time', '链接有效期开始时间', 'string', false);
                $this->I('url_end_time', '链接有效期结束时间', 'string', false);
                $this->I('extra_type', '扩展商品类型', 'string', false);

                $this->I('level', '商品等级必需', 'int', false);
                $this->I('cool_val', '商品炫酷值必需', 'int', false);
                $this->I('renew_card_num', '商品续签加油卡数量', 'int', false);
                $this->I('debris_num', '商品可回收碎片数量', 'int', false);
                $this->I('is_upgrade', '商品升级属性', 'int', false);
                $this->I('upgrade_config', '商品升级配置', 'array', false);
                $this->I('mall_goods_class', '商品商品分类', 'int', false);

                $variables = [];
                $checkParams = $this->check($this->requestData, $variables); //校验数据
                extract($checkParams);
                if ($code !== Hint::SUCCESS) {
                    break;
                }

                $upgrade_config = $this->requestData['upgrade_config'] ?? [];
                unset($this->requestData['upgrade_config']);

                if ($this->requestData['is_upgrade']==1 && empty($upgrade_config)){
                    throw new \Exception("可升级商品升级配置缺失");
                }
                if ($this->requestData['is_upgrade']==0) {
                    $upgrade_config = [];
                }

//                $this->mallGoods -> delGoodsUpConfigByGid();
                $GoodsConfigData = [];
                if ($upgrade_config){
                    $upgrade_level = 1;
                    foreach ((array)$upgrade_config as $key => $value) {
                        $item = [];
                        $item['level'] = (int) $upgrade_level;
                        $item['level_name'] = (string) $value['level_name'];
                        $item['intimate'] = (int) $value['intimate'];
                        $item['intimate_max'] = (int) $value['intimate_max'];
                        $item['img'] = $value['img']??'';
                        $item['animate'] = $value['animate']??'';
                        $item['animate_md5'] = $value['animate_md5']??'';
                        $item['add_time'] = time();
                        $upgrade_level++;
                        array_push($GoodsConfigData, $item);
                    }
                }

                write_log(
                    'MallServices'.(isCli()?'-cli':''),
                    '[INFO] 商品添加-佩戴升级配置',
                    $GoodsConfigData
                );

                extract($variables); //数组参数化

                $this->requestData['create_timestamp'] = time();

                DB::beginTransaction();
                $data['goods_id'] = $this->mallGoods->insertSingle($this->requestData);
                if ($data['goods_id'] <= 0) {
                    $code = Hint::ERR_DATA_CREATE_FAIL;
                    $msg = '商品' . Hint::getErrCodeMsg($code);
                    break;
                }
                $Gid = $data['goods_id'];

                if ($GoodsConfigData){
                    $GoodsConfigData = array_map(function ($val)use($Gid){
                        $val['goods_id'] = $Gid;
                        return $val;
                    }, $GoodsConfigData);

                    $ResGuConfig = $this->mallGoods -> createGoodsUpConfig($GoodsConfigData);
                    if (!$ResGuConfig){
                        throw new \Exception("商品升级配置错误");
                    }
                }
                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                $code = Hint::ERR_SYS_FAIL;
                $msg = 'message：' . $e->getMessage() . '，line：' . $e->getLine();
                break;
            }
        } while (false);

        write_log(
            'MallServices'.(isCli()?'-cli':''),
            ($code!=0 ? '[ERROR]': '[INFO]') . '商品添加',
            ['msg'=>$msg, 'params'=>$this->requestData]
        );
        return compact('code', 'msg', 'data');
    }

    /**
     * 商品标签创建
     */
    public function labelCreate()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            try {
                $this->I('name', '标签名称', 'string', true, '标签名称不能为空');
                $this->I('resource', '标签图片', 'string', true, '标签图片不能为空');

                $variables = [];
                $checkParams = $this->check($this->requestData, $variables); //校验数据
                extract($checkParams);
                if ($code !== Hint::SUCCESS) {
                    break;
                }
                extract($variables); //数组参数化

                $this->mallGoods->table = 'mall_goods_label';
                $data['label_id'] = $this->mallGoods->insertSingle($this->requestData);
                if ($data['label_id'] <= 0) {
                    $code = Hint::ERR_DATA_CREATE_FAIL;
                    $msg = '商品标签' . Hint::getErrCodeMsg($code);
                    break;
                }

            } catch (\Exception $e) {
                $code = Hint::ERR_SYS_FAIL;
                $msg = 'message：' . $e->getMessage() . '，line：' . $e->getLine();
                break;
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 商品标签编辑
     * @return array
     */
    public function labelEdit()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            try {
                $this->I('id', '标签ID', 'string', true, '标签ID不能为空');
                $this->I('name', '标签名称', 'string', true, '标签名称不能为空');
                $this->I('resource', '标签图片', 'string', true, '标签图片不能为空');

                $variables = [];
                $checkParams = $this->check($this->requestData, $variables); //校验数据
                extract($checkParams);
                if ($code !== Hint::SUCCESS) {
                    break;
                }
                extract($variables); //数组参数化

                $this->mallGoods->table = 'mall_goods_label';
                $id = $this->requestData['id'];
                unset($this->requestData['id']);
                $data['label_id'] = $this->mallGoods->singleUpdate(['id' => $id], $this->requestData);
                if ($data['label_id'] <= 0) {
                    $code = Hint::ERR_DATA_UPDATE_FAIL;
                    $msg = '商品标签' . Hint::getErrCodeMsg($code);
                    break;
                }

            } catch (\Exception $e) {
                $code = Hint::ERR_SYS_FAIL;
                $msg = 'message：' . $e->getMessage() . '，line：' . $e->getLine();
                break;
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 商品更新
     * */
    public function goodsUpdate()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            try {
                $this->I('goods_id', '商品ID', 'int', true, '商品ID不能为空');
                $this->I('goods_name', '商品名称', 'string', false, '商品名称不能为空');
                $this->I('goods_type', '商品类型', 'int', false, '商品类型不能为空');// 0:其他 1:头饰 2:进场特效 3:气泡
//                $this->I('is_new', '是否新品', 'int', false, '是否新品不能为空');// 0:否 1:是
                $this->I('is_show', '是否显示商品', 'int', false);// 0:否 1:是
                $this->I('is_new_mount', '是否是新进场特效', 'int', false);// 0:否 1:是
                $this->I('text_color', '进场条字体颜色', 'string', false);
                $this->I('sort', '商品显示排序', 'int', false);// 值越大越靠前
                $this->I('big_img', '预览图片 (大图)', 'string', false,'预览图片 (大图)不能为空');
                $this->I('small_img', '展示图片（小图）', 'string', false,'展示图片（小图）不能为空');
                $this->I('animate_resource', '动画资源包链接', 'string', false,'动画资源包链接不能为空');
                $this->I('animate_resource_md5', '动画资源md5值', 'string', false);
                $this->I('animate_resource_small', '动画资源链接（默认小资源）', 'string', false);
                $this->I('animate_resource_big', '动画资源链接（新资料卡资源）', 'string', false);
                $this->I('vapc_json_url', '动画vapc资源', 'string', false);
                $this->I('give_data_id', 'give_data_id', 'int', false);
                $this->I('goods_desc', '商品描述', 'string', false);
                $this->I('is_buy', '是否需要购买', 'int', false); //1:是 0:否
                $this->I('from_url', '获取途径url', 'string', false);
                $this->I('from_desc', '获取途径描述', 'string', false);
                $this->I('label_id', '标签ID', 'string', false);
                $this->I('url_start_time', '链接有效期开始时间', 'string', false);
                $this->I('url_end_time', '链接有效期结束时间', 'string', false);
                $this->I('extra_type', '扩展商品类型', 'string', false);

                $this->I('level', '商品等级必需', 'int', false);
                $this->I('cool_val', '商品炫酷值必需', 'int', false);
                $this->I('renew_card_num', '商品续签加油卡数量', 'int', false);
                $this->I('debris_num', '商品可回收碎片数量', 'int', false);
                $this->I('is_upgrade', '商品升级属性', 'int', false);
                $this->I('upgrade_config', '商品升级配置', 'array', false);
                $this->I('mall_goods_class', '商品商品分类', 'int', false);

                $variables = [];
                $checkParams = $this->check($this->requestData, $variables); //校验数据
                extract($checkParams);
                if ($code !== Hint::SUCCESS) {
                    break;
                }
                extract($variables); //数组参数化

                $goodsId = $this->requestData['goods_id'];
                // 移除请求数据中的ID
                unset($this->requestData['goods_id']);
                $upgrade_config = $this->requestData['upgrade_config'] ?? [];
                unset($this->requestData['upgrade_config']);
                if ($this->requestData['is_upgrade']==1 && empty($upgrade_config)){
                    throw new \Exception("可升级商品升级配置缺失");
                }

                if ($this->requestData['is_upgrade']==0) {
                    $upgrade_config = [];
                }


                if (empty($this->requestData)) {
                    $code = Hint::ERR_PARAMS_CHECK_FAIL;
                    $msg = Hint::getErrCodeMsg($code) . ':至少包含任意一个业务参数';
                    break;
                }

                $ret = $this->mallGoods->singleUpdate(['goods_id' => $goodsId], $this->requestData);
                /*if (!$ret) {
                    $code = Hint::ERR_DATA_UPDATE_FAIL;
                    $msg = '商品' . Hint::getErrCodeMsg($code);
                    break;
                }*/

                $GoodsConfigData = [];
                if ($upgrade_config){
                    $upgrade_level = 1;
                    foreach ((array)$upgrade_config as $key => $value) {
                        $item = [];
                        $item['level'] = (int) $upgrade_level;
                        $item['level_name'] = (string) $value['level_name'];
                        $item['intimate'] = (int) $value['intimate'];
                        $item['intimate_max'] = (int) $value['intimate_max'];
                        $item['img'] = $value['img']??'';
                        $item['animate'] = $value['animate']??'';
                        $item['animate_md5'] = $value['animate_md5']??'';
                        $item['add_time'] = time();
                        $upgrade_level++;
                        array_push($GoodsConfigData, $item);
                    }
                }
                write_log(
                    'MallServices'.(isCli()?'-cli':''),
                    '[INFO] 商品编辑-佩戴升级配置',
                    $GoodsConfigData
                );

                $this->mallGoods -> delGoodsUpConfigByGid($goodsId);

                if ($GoodsConfigData){
                    $GoodsConfigData = array_map(function ($val)use($goodsId){
                        $val['goods_id'] = $goodsId;
                        return $val;
                    }, $GoodsConfigData);

                    $ResGuConfig = $this->mallGoods -> createGoodsUpConfig($GoodsConfigData);
                    if (!$ResGuConfig){
                        throw new \Exception("商品升级配置错误");
                    }
                }

                $data['goods_id'] = intval($goodsId);

            } catch (\Exception $e) {
                $code = Hint::ERR_SYS_FAIL;
                $msg = 'message：' . $e->getMessage() . '，line：' . $e->getLine();
                break;
            }
        } while (false);

        write_log(
            'MallServices'.(isCli()?'-cli':''),
            ($code!=0 ? '[ERROR]': '[INFO]') . '商品编辑',
            ['msg'=>$msg, 'params'=>$this->requestData]
        );
        return compact('code', 'msg', 'data');
    }

    /**
     * 商品删除
     * */
    public function goodsRemove()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            try {
                $this->I('goods_id', '商品ID', 'int', true, '商品ID不能为空');

                $variables = [];
                $checkParams = $this->check($this->requestData, $variables); //校验数据
                extract($checkParams);
                if ($code !== Hint::SUCCESS) {
                    break;
                }
                extract($variables); //数组参数化

                // 删除商品数据
                $ret = $this->mallGoods->singleRemove($this->requestData);
                if (!$ret) {
                    $code = Hint::ERR_DATA_REMOVE_FAIL;
                    $msg = '商品' . Hint::getErrCodeMsg($code);
                    break;
                }

                // 删除商品规格数据
                $this->mallGoodsSku->singleRemove($this->requestData);

                // 删除佩戴升级配置
                $GID = $this->requestData['goods_id'] ?? 0;
                $this->mallGoods-> delGoodsUpConfigByGid($GID);

            } catch (\Exception $e) {
                $code = Hint::ERR_SYS_FAIL;
                $msg = 'message：' . $e->getMessage() . '，line：' . $e->getLine();
                break;
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 商品规格创建
     * */
    public function goodsSkuCreate()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            try {
                $this->I('goods_id', '商品ID', 'int', true, '商品ID不能为空');
                $this->I('time_limit', '使用有效期限', 'int', true, '使用有效期限不能为空');//  单位：天
                $this->I('price', '价格', 'int', true, '价格不能为空');// 单位：钻石
                $this->I('default', '是否默认', 'int', false);// 0.非默认 1.默认

                $variables = [];
                $checkParams = $this->check($this->requestData, $variables); //校验数据
                extract($checkParams);
                if ($code !== Hint::SUCCESS) {
                    break;
                }
                extract($variables); //数组参数化

                // 更新商品所属全部规格设置为非默认
                if(isset($this->requestData['default']) and $this->requestData['default'] == 1){
                    $checkData = $this->mallGoodsSku->getSingle(['goods_id' => $this->requestData['goods_id'],'default' => 1], ['sku_id','goods_id']);
                    if(!empty($checkData)){
                        $this->mallGoodsSku->singleUpdate(['goods_id' => $this->requestData['goods_id']], ['default' => 0]);
                    }
                }

                $this->requestData['create_timestamp'] = time();
                // 创建规格
                $data['sku_id'] = $this->mallGoodsSku->insertSingle($this->requestData);
                if ($data['sku_id'] <= 0) {
                    $code = Hint::ERR_DATA_CREATE_FAIL;
                    $msg = '商品规格' . Hint::getErrCodeMsg($code);
                    break;
                }

            } catch (\Exception $e) {
                $code = Hint::ERR_SYS_FAIL;
                $msg = 'message：' . $e->getMessage() . '，line：' . $e->getLine();
                break;
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 商品规格更新
     * */
    public function goodsSkuUpdate()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            try {
                $this->I('sku_id', '商品规格ID', 'int', true, '商品规格ID不能为空');
                $this->I('goods_id', '商品ID', 'int', true, '商品ID不能为空');
                $this->I('time_limit', '使用有效期限', 'int', false, '使用有效期限不能为空');//  单位：天
                $this->I('price', '价格', 'int', false, '价格不能为空');// 单位：钻石
                $this->I('default', '是否默认', 'int', false);// 0.非默认 1.默认

                $variables = [];
                $checkParams = $this->check($this->requestData, $variables); //校验数据
                extract($checkParams);
                if ($code !== Hint::SUCCESS) {
                    break;
                }
                extract($variables); //数组参数化

                $skuId = $this->requestData['sku_id'];
                $goodsId = $this->requestData['goods_id'];
                // 移除请求数据中的ID
                unset($this->requestData['sku_id']);
                unset($this->requestData['goods_id']);

                if (empty($this->requestData)) {
                    $code = Hint::ERR_PARAMS_CHECK_FAIL;
                    $msg = Hint::getErrCodeMsg($code) . ':至少包含任意一个业务参数';
                    break;
                }

                // 更新商品所属全部规格设置为非默认
                if(isset($this->requestData['default']) and $this->requestData['default'] == 1){
                    $checkData = $this->mallGoodsSku->getSingle(['goods_id' => $goodsId,'default' => 1], ['sku_id','goods_id']);
                    if(!empty($checkData)){
                        $this->mallGoodsSku->singleUpdate(['goods_id' => $goodsId], ['default' => 0]);
                    }
                }

                // 更新规格
                $ret = $this->mallGoodsSku->singleUpdate(['sku_id' => $skuId,'goods_id' => $goodsId], $this->requestData);
                if (!$ret) {
                    $code = Hint::ERR_DATA_UPDATE_FAIL;
                    $msg = '商品规格' . Hint::getErrCodeMsg($code);
                    break;
                }

                $data['sku_id'] = intval($skuId);

            } catch (\Exception $e) {
                $code = Hint::ERR_SYS_FAIL;
                $msg = 'message：' . $e->getMessage() . '，line：' . $e->getLine();
                break;
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 商品规格删除
     * */
    public function goodsSkuRemove()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            $code = Hint::PARAM_ERROR;
            $msg = '不可删除,为啥要删除SKU?';
            break;

            try {
                $this->I('sku_id', '商品规格ID', 'int', true, '商品规格ID不能为空');

                $variables = [];
                $checkParams = $this->check($this->requestData, $variables); //校验数据
                extract($checkParams);
                if ($code !== Hint::SUCCESS) {
                    break;
                }
                extract($variables); //数组参数化

                $ret = $this->mallGoodsSku->singleRemove($this->requestData);
                if (!$ret) {
                    $code = Hint::ERR_DATA_REMOVE_FAIL;
                    $msg = '商品规格' . Hint::getErrCodeMsg($code);
                    break;
                }

            } catch (\Exception $e) {
                $code = Hint::ERR_SYS_FAIL;
                $msg = 'message：' . $e->getMessage() . '，line：' . $e->getLine();
                break;
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    public function createMallUnionGoods(array $data = []) {
        if($this->mallGoods->getMallUnionGoodsByCondition([ 'union_id' => $data['union_id'] ])) {
            return Hint::PARAM_ERROR;
        }
        $this->mallGoods->createMallUnionGoods($data);
        return Hint::SUCCESS;
    }

    public function updateMallUnionGoods(int $id, array $data = []) {
        try{
            if($this->mallGoods->checkMallUnionGoods($data['union_id'], $id)) {
                return Hint::PARAM_ERROR;
            }
            $this->mallGoods->updateMallUnionGoods($id, $data);
        }catch(Exception $e) {
            return Hint::PARAM_ERROR;
        }
        return Hint::SUCCESS;
    }
}
